#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "memorypool.h"
#include <QScrollBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    taskManager = new TaskManager();
    // 定时更新内存池状态
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updatePoolStatus);
    timer->start(300);
    // 配置栏
    updateConfig();
    // 按钮启用
    connect(this, &MainWindow::buttonStateChanged, this, &MainWindow::onButtonStateChanged);
    emit buttonStateChanged(false);
    // 任务列表更新
    connect(taskManager, &TaskManager::taskBatchAdded, this, &MainWindow::onTaskBatchAdded);
    connect(taskManager, &TaskManager::taskRemoved, this, &MainWindow::onTaskRemoved);
    connect(taskManager, &TaskManager::taskListCleared, this, &MainWindow::onTaskListCleared);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete taskManager;
}

void MainWindow::updatePoolStatus()
{
    ui->poolWidget->setRowCount(MEMORY_POOL_NUM);
    ui->poolWidget->setColumnCount(3);
    ui->poolWidget->setHorizontalHeaderLabels({"池", "使用情况", "操作"});
    ui->poolWidget->setColumnWidth(0, 100);  // 第一列固定宽度
    ui->poolWidget->setColumnWidth(2, 100);  // 第三列固定宽度
    ui->poolWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);  // 第一列固定
    ui->poolWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);  // 第二列自适应
    ui->poolWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Fixed);  // 第三列固定

    for (int i = 0; i < MEMORY_POOL_NUM; i++) {
        PoolStatus status = HashBucket::getPoolStatus(i);
        // 池信息
        ui->poolWidget->setItem(i, 0, new QTableWidgetItem(
            QString("池%1(%2B)").arg(status.poolIdx).arg(status.slotSize)));
        // 使用情况
        if(!status.isInitialized()) {
            ui->poolWidget->setItem(i, 1, new QTableWidgetItem("未初始化"));
        } else {
            QString visualInfo = createPoolView(status);
            ui->poolWidget->setItem(i, 1, new QTableWidgetItem(visualInfo));
        }
        // 操作
        // 详情按钮
        QPushButton* detailBtn = new QPushButton("详情");
        ui->poolWidget->setCellWidget(i, 2, detailBtn);
    }
    // 设置行高自适应
    ui->poolWidget->resizeRowsToContents();
}

QString MainWindow::createPoolView(const PoolStatus& status)
{
    // 第一行：方块和进度条等可视化图形
    QString visualInfo = createBlockIndicator(status) + " " +createUsageBar(status);
    // 第二行：文字信息
    QString textInfo = createPoolTextInfo(status);
    return visualInfo + "\n" + textInfo;
}
QString MainWindow::createBlockIndicator(const PoolStatus& status)
{
    if (!status.isInitialized()) {
        return "";  // 未初始化或未分配块
    }
    if (status.blockCnt == 0) {
        return "□";
    }
    
    QString indicators;
    int totalBlocks = status.blockCnt;
    int usedSlots = status.usedSlotCnt;
    int totalSlots = status.totalSlotCnt;
    
    // 计算每个块的状态
    for (int i = 0; i < totalBlocks; i++) {
        int blockStartSlot = (i * totalSlots) / totalBlocks;
        int blockEndSlot = ((i + 1) * totalSlots) / totalBlocks;
        
        if (usedSlots >= blockEndSlot) {
            indicators += "■";  // 块已满
        } else if (usedSlots > blockStartSlot) {
            indicators += "▣";  // 块部分使用
        } else {
            indicators += "□";  // 块空闲
        }
    }
    
    return indicators;
}
QString MainWindow::createUsageBar(const PoolStatus& status)
{
    const int BAR_LENGTH = 30;  // 进度条长度
    
    if (!status.isInitialized()) {
        return "";
    }
    if (status.totalSlotCnt == 0) {
        return QString(BAR_LENGTH, QChar(0x2591));  // ░ 的Unicode编码
    }
    
    double usageRate = (double)status.usedSlotCnt / status.totalSlotCnt;
    int filledLength = (int)(usageRate * BAR_LENGTH);
    
    return QString(filledLength, QChar(0x2588)) + QString(BAR_LENGTH - filledLength, QChar(0x2591));
}
QString MainWindow::createPoolTextInfo(const PoolStatus& status)
{
    double usageRate = status.totalSlotCnt > 0 ? (double)status.usedSlotCnt / status.totalSlotCnt * 100 : 0;
    return QString("块数:%1 状态:%2 已用 %3/%4 槽 (%5%)")
            .arg(status.blockCnt)
            .arg(status.getPoolState())
            .arg(status.usedSlotCnt)
            .arg(status.totalSlotCnt)
            .arg(usageRate, 0, 'f', 1);
}

void MainWindow::updateConfig()
{
    ui->poolNumLabel->setText(QString("内存池数量: %1").arg(MEMORY_POOL_NUM));
    ui->slotSizeLabel->setText(QString("基础槽大小: %1B").arg(SLOT_BASE_SIZE));
    ui->blockSizeLabel->setText(QString("块大小: %1KB").arg(BLOCK_SIZE / 1024));
}

void MainWindow::on_initPoolButton_clicked()
{
    HashBucket::initMemoryPool();
    emit buttonStateChanged(true);
}

void MainWindow::on_resetPoolButton_clicked()
{
    taskManager->clearTaskList();
    HashBucket::initMemoryPool();
    emit buttonStateChanged(false);
}


void MainWindow::on_allocateButton_clicked()
{
    int taskNum = ui->taskNumSpinBox->value();
    size_t memSize = ui->memorySizeSpinBox->value();
    for (int i = 0; i < taskNum; i++) {
        TaskInfo task = taskManager->createTask(memSize);
        if (task.allocatedPtr) {
            taskManager->addTask(task);
        }
    }
    taskManager->batchUpdate(); // 批量添加任务
}


void MainWindow::on_pressureTestButton_clicked()
{

}


void MainWindow::onButtonStateChanged(bool isPoolInitialized)
{
    ui->initPoolButton->setEnabled(!isPoolInitialized);
    ui->resetPoolButton->setEnabled(isPoolInitialized);
    ui->allocateButton->setEnabled(isPoolInitialized);
    ui->pressureTestButton->setEnabled(isPoolInitialized);
}




void MainWindow::onTaskBatchAdded()
{
    const auto& currentTaskList = taskManager->getTaskList();
    int currentRowCount = ui->taskListWidget->rowCount();
    int newRowCount = currentTaskList.size();
    
    // 增量更新：只添加新行
    if (newRowCount > currentRowCount) {
        for (int row = currentRowCount; row < newRowCount; ++row) {
            const TaskInfo& task = currentTaskList[row];
            
            ui->taskListWidget->insertRow(row);
            
            // 设置任务ID
            ui->taskListWidget->setItem(row, 0, new QTableWidgetItem(QString::number(task.taskId)));
            // 设置任务大小
            ui->taskListWidget->setItem(row, 1, new QTableWidgetItem(QString("%1B").arg(task.memSize)));
            // 设置任务分配池
            ui->taskListWidget->setItem(row, 2, new QTableWidgetItem(QString("池%1").arg(task.poolIdx)));
            // 设置任务分配时间
            ui->taskListWidget->setItem(row, 3, new QTableWidgetItem(task.timestamp));
            // 设置释放按钮
            QPushButton* releaseBtn = new QPushButton("释放");
            connect(releaseBtn, &QPushButton::clicked, [this, taskId = task.taskId]() {
                taskManager->removeTask(taskId);
            });
            ui->taskListWidget->setCellWidget(row, 4, releaseBtn);
        }
    }
    // 滚动到最底部
    ui->taskListWidget->scrollToBottom();
}

void MainWindow::onTaskRemoved(int taskId)
{
    // 记住当前滚动条位置
    int scrollBarPos = ui->taskListWidget->verticalScrollBar()->value();
    
    // 删除任务：在UI里查找对比，删除对应的行
    for (int row = 0; row < ui->taskListWidget->rowCount(); ++row) {
        QTableWidgetItem* item = ui->taskListWidget->item(row, 0);
        if (item && item->text().toInt() == taskId) {
            ui->taskListWidget->removeRow(row);
            break;
        }
    }
    
    // 恢复滚动条位置
    ui->taskListWidget->verticalScrollBar()->setValue(scrollBarPos);
}

void MainWindow::onTaskListCleared()
{
    // 清空任务列表：直接清空表格
    ui->taskListWidget->setRowCount(0);
}
